"""
注：本程序以txt（通讯录.txt）格式存储联系人信息，其中每个联系人信息以一个字符串形式存入通讯录.txt文件中，每行存储一个联系人信息，存储时要加入行结束符\n（这是txt文件的特点要求）.
由于每行是一个字符串，其中姓名，电话，QQ号码，邮箱之间以逗号,分隔，因此要读取其中"姓名"（是字符串的第一个元素）时，要先将串分离 line.strip().split(',')，然后读取第一个用索引读取第1个元素
"""

#方法一，文件读写没有单独构成函数
def create_contact():
    while True:
        name = input("请输入联系人姓名: ")
        phone = input("请输入联系人电话: ")
        qq = input("请输入联系人QQ号码: ")
        email = input("请输入联系人邮箱: ")
        contact_str = f"{name},{phone},{qq},{email}\n"
        try:
            with open('通讯录.txt', 'r+',encoding='utf-8') as file:
                # 检查文件是否为空，如果是则添加表头
                if file.read().strip() == '':
                    file.write("姓名,电话,QQ,邮箱\n")
                # 将文件指针移到文件末尾
                file.seek(0, 2)
                file.write(contact_str)
        except FileNotFoundError:
            # 如果文件不存在，新建文件并写入表头和联系人信息
            with open('通讯录.txt', 'w',encoding='utf-8') as file:
                file.write("姓名,电话,QQ,邮箱\n")
                file.write(contact_str)

        print("联系人添加成功！")
        # 询问用户是否继续添加
        continue_adding = input("是否继续添加联系人(Y/N)?")
        if continue_adding == 'Y' or continue_adding == 'y':
            continue
        else:
            break

def show_contact():
    try:
        with open('通讯录.txt', 'r',encoding='utf-8') as file:
            lines = file.readlines()
            if len(lines) < 2:
                print("通讯录为空!")
                return
            print("通讯录中的联系人信息如下：")
            # 跳过表头，从第二行开始是联系人数据
            for line in lines[1:]:
                # 去除换行符并按逗号分割
                contact_details = line.strip().split(',')
                print(f"姓名: {contact_details[0]}, 电话: {contact_details[1]}, QQ: {contact_details[2]}, 邮箱: {contact_details[3]}")
    except FileNotFoundError:
        print("通讯录文件未找到!")

def search_contact():
    search_name = input("请输入要查询的联系人姓名: ")
    try:
        with open('通讯录.txt', 'r',encoding='utf-8') as file:
            lines = file.readlines()
            found = False
            # 从第二行开始检查每一行
            for line in lines[1:]:
                # 分割行数据
                contact_details = line.strip().split(',')
                if contact_details[0] == search_name:
                    print(f"找到的联系人{search_name}的信息是:")
                    print(f"姓名: {contact_details[0]}, 电话: {contact_details[1]}, QQ: {contact_details[2]}, 邮箱: {contact_details[3]}")
                    found = True
                    break
            if not found:
                print("未找到该联系人!")
    except FileNotFoundError:
        print("通讯录文件不存在!")

def delete_contact():
    delete_name = input("请输入要删除的联系人姓名: ")
    try:
        with open('通讯录.txt', 'r',encoding='utf-8') as file:
            lines = file.readlines()
        # 准备一个新列表，用于保存未被删除的联系人
        new_lines = []
        found = False
        for line in lines:
            # 分割行数据
            contact_details = line.strip().split(',')
            if contact_details[0] != delete_name:
                # 如果不是要删除的联系人，就添加到新列表中
                new_lines.append(line)
            else:
                found = True
        if found:
            # 重新写入更新后的联系人数据
            with open('通讯录.txt', 'w',encoding='utf-8') as file:
                file.writelines(new_lines)
            print(f"联系人{delete_name}已被删除!")
        else:
            print("未找到该联系人!")
    except FileNotFoundError:
        print("通讯录文件未找到!")

def modify_contact():
    modify_name = input("请输入要修改的联系人姓名: ")
    try:
        with open('通讯录.txt', 'r',encoding='utf-8') as file:
            lines = file.readlines()
        # 准备一个新列表，用于保存更新后的联系人信息
        new_lines = []
        found = False
        for line in lines:
            contact_details = line.strip().split(',')
            if contact_details[0] == modify_name:
                print(f"找到了联系人{modify_name}，请输入新的联系人信息：")
                new_name = input("新姓名: ")
                new_phone = input("新电话: ")
                new_qq = input("新QQ号码: ")
                new_email = input("新邮箱: ")
                updated_contact = f"{new_name},{new_phone},{new_qq},{new_email}\n"
                new_lines.append(updated_contact)
                found = True
            else:
                new_lines.append(line)
        if found:
            with open('通讯录.txt', 'w',encoding='utf-8') as file:
                file.writelines(new_lines)
            print(f"联系人{modify_name}的信息已更新!")
        else:
            print("未找到该联系人!")
    except FileNotFoundError:
        print("通讯录文件未找到!")

def main():
    while True:
        # 打印菜单选项
        print("\n通讯录管理系统")
        print("*"*30)
        print("1. 添加联系人")
        print("2. 显示所有联系人")
        print("3. 搜索联系人")
        print("4. 删除联系人")
        print("5. 修改联系人")
        print("6. 退出程序")
        print("*" * 30)
        # 获取用户的选择
        choice = input("请选择一个操作（输入数字1-6）: ")
        if choice == '1':
            create_contact()
        elif choice == '2':
            show_contact()
        elif choice == '3':
            search_contact()
        elif choice == '4':
            delete_contact()
        elif choice == '5':
            modify_contact()
        elif choice == '6':
            exit_confirm = input("是否确认退出(Y/N)?")
            if exit_confirm == 'Y' or exit_confirm == 'y':
                print("感谢使用通讯录管理系统，再见！")
                break
            else:
                continue
        else:
            print("无效的输入，请输入1-6之间的数字!")

if __name__ == "__main__":
    main()


#方法二，将文件读写单独构成函数，根据需要调用

def read_contacts():
    try:
        with open('data/通讯录.txt', 'r',encoding='utf-8') as file:
            return file.readlines()
    except FileNotFoundError:
        return None

def write_contacts(lines):
    with open('data/通讯录.txt', 'w',encoding='utf-8') as file:
        file.writelines(lines)

def create_contact():
    while True:
        name = input("请输入联系人姓名: ")
        phone = input("请输入联系人电话: ")
        qq = input("请输入联系人QQ号码: ")
        email = input("请输入联系人邮箱: ")
        contact_str = f"{name},{phone},{qq},{email}\n"

        lines = read_contacts()
        if lines is None or not lines:
            lines = ["姓名,电话,QQ,邮箱\n"]
        lines.append(contact_str)
        write_contacts(lines)

        print("联系人添加成功！")
        # 询问用户是否继续添加
        continue_adding = input("是否继续添加联系人(Y/N)?")
        if continue_adding == 'Y' or continue_adding == 'y':
            continue
        else:
            break

def show_contact():
    lines = read_contacts()
    if lines is None or len(lines) < 2:
        print("通讯录为空！")
        return
    print("通讯录中的联系人信息如下：")
    # 跳过表头，从第二行开始是联系人数据
    for line in lines[1:]:
        contact_details = line.strip().split(',')
        print(f"姓名: {contact_details[0]}, 电话: {contact_details[1]}, QQ: {contact_details[2]}, 邮箱: {contact_details[3]}")

def search_contact():
    search_name = input("请输入要查询的联系人姓名: ")
    lines = read_contacts()
    if lines is None:
        print("通讯录文件未找到！")
        return
    found = False
    for line in lines[1:]:
        contact_details = line.strip().split(',')
        if contact_details[0] == search_name:
            print(f"找到的联系人{search_name}的信息是:")
            print(f"姓名: {contact_details[0]}, 电话: {contact_details[1]}, QQ: {contact_details[2]}, 邮箱: {contact_details[3]}")
            found = True
            break
    if not found:
        print(f"未找到该联系人{search_name}！")

def delete_contact():
    delete_name = input("请输入要删除的联系人姓名: ")
    lines = read_contacts()
    if lines is None:
        print("通讯录文件未找到!")
        return
    # 准备一个新列表，用于保存未被删除的联系人，其中已存入表头
    new_lines = [lines[0]]
    found = False
    for line in lines[1:]:
        if line.split(',')[0] != delete_name:
            new_lines.append(line)
        else:
            found = True
    if found:
        write_contacts(new_lines)
        print(f"联系人{delete_name}已被删除!")
    else:
        print(f"未找到该联系人{delete_name}!")

def modify_contact():
    modify_name = input("请输入要修改的联系人姓名: ")
    lines = read_contacts()
    if lines is None:
        print("通讯录文件未找到！")
        return
    new_lines = [lines[0]]
    found = False
    for line in lines[1:]:
        contact_details = line.strip().split(',')
        if contact_details[0] == modify_name:
            print(f"找到了联系人{modify_name}，请输入新的联系人信息：")
            new_name = input("新姓名: ")
            new_phone = input("新电话: ")
            new_qq = input("新QQ号码: ")
            new_email = input("新邮箱: ")
            updated_contact = f"{new_name},{new_phone},{new_qq},{new_email}\n"
            new_lines.append(updated_contact)
            found = True
        else:
            new_lines.append(line)
    if found:
        write_contacts(new_lines)
        print(f"联系人{modify_name}的信息已更新！")
    else:
        print(f"未找到该联系人{modify_name}！")

def main():
    while True:
        # 打印菜单选项
        print("\n通讯录管理系统")
        print("*"*30)
        print("1. 添加联系人")
        print("2. 显示所有联系人")
        print("3. 搜索联系人")
        print("4. 删除联系人")
        print("5. 修改联系人")
        print("6. 退出程序")
        print("*" * 30)
        # 获取用户的选择
        choice = input("请选择一个操作（输入数字1-6）: ")
        if choice == '1':
            create_contact()
        elif choice == '2':
            show_contact()
        elif choice == '3':
            search_contact()
        elif choice == '4':
            delete_contact()
        elif choice == '5':
            modify_contact()
        elif choice == '6':
            exit_confirm = input("是否确认退出(Y/N)?")
            if exit_confirm == 'Y' or exit_confirm == 'y':
                print("感谢使用通讯录管理系统，再见！")
                break
            else:
                continue
        else:
            print("无效的输入，请输入1-6之间的数字!")

if __name__ == "__main__":
    main()
